package com.rainkaze.lifeharbor.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.rainkaze.lifeharbor.R;
import com.rainkaze.lifeharbor.adapter.ToolAdapter;
import com.rainkaze.lifeharbor.databinding.FragmentItemAllBinding;
import com.rainkaze.lifeharbor.db.DatabaseHelper;
import com.rainkaze.lifeharbor.model.ToolItem;
import com.rainkaze.lifeharbor.utils.ToolRepository;

import java.util.ArrayList;
import java.util.List;

public class AllItemFragment extends Fragment implements ToolAdapter.OnToolClickListener {

    private FragmentItemAllBinding binding;
    private ToolAdapter toolAdapter;
    private List<ToolItem> toolItemList;
    private DatabaseHelper dbHelper;

    private static final String KEY_LAYOUT_MANAGER_TYPE = "layout_manager_type";
    private enum LayoutManagerType {
        FLEXBOX, GRID_ONE_COLUMN, GRID_TWO_COLUMNS, GRID_THREE_COLUMNS
    }
    private LayoutManagerType currentLayoutManagerType = LayoutManagerType.FLEXBOX;

    public AllItemFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        dbHelper = new DatabaseHelper(getContext());
        if (savedInstanceState != null) {
            if (savedInstanceState.containsKey(KEY_LAYOUT_MANAGER_TYPE)) {
                currentLayoutManagerType = (LayoutManagerType) savedInstanceState.getSerializable(KEY_LAYOUT_MANAGER_TYPE);
            }
        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentItemAllBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        toolItemList = new ArrayList<>();
        prepareToolDataAndLoadFavorites();

        toolAdapter = new ToolAdapter(getContext(), toolItemList, this);
        binding.recyclerViewTools.setAdapter(toolAdapter);
        updateRecyclerViewLayoutManager(currentLayoutManagerType);
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(KEY_LAYOUT_MANAGER_TYPE, currentLayoutManagerType);
    }

    private void prepareToolDataAndLoadFavorites() {
        toolItemList.clear();

        List<ToolItem> baseToolList = ToolRepository.getBaseToolList();

        for (ToolItem item : baseToolList) {
            item.setFavorite(dbHelper.isToolFavorite(item.getToolIdentifier()));
            toolItemList.add(item);
        }

        if (toolAdapter != null) {
            toolAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (toolItemList != null && dbHelper != null && toolAdapter != null) {
            boolean needsRefresh = false;
            for (ToolItem item : toolItemList) {
                boolean currentDbFavorite = dbHelper.isToolFavorite(item.getToolIdentifier());
                if (item.isFavorite() != currentDbFavorite) {
                    item.setFavorite(currentDbFavorite);
                    needsRefresh = true;
                }
            }
            if (needsRefresh) {
                toolAdapter.notifyDataSetChanged();
            }
        }
    }


    @Override
    public void onToolClick(ToolItem toolItem, int position) {
        if (toolItem.getTargetActivityClass() != null && getActivity() != null) {
            Intent intent = new Intent(getActivity(), toolItem.getTargetActivityClass());
            getActivity().startActivity(intent);
        } else {
            Toast.makeText(getContext(), "该工具页面尚未配置: " + toolItem.getName(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_all_items_layout, menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.action_layout_flexwrap) {
            updateRecyclerViewLayoutManager(LayoutManagerType.FLEXBOX);
            item.setChecked(true);
            return true;
        } else if (itemId == R.id.action_layout_grid_one_column) {
            updateRecyclerViewLayoutManager(LayoutManagerType.GRID_ONE_COLUMN);
            item.setChecked(true);
            return true;
        } else if (itemId == R.id.action_layout_grid_two_columns) {
            updateRecyclerViewLayoutManager(LayoutManagerType.GRID_TWO_COLUMNS);
            item.setChecked(true);
            return true;
        } else if (itemId == R.id.action_layout_grid_three_columns) {
            updateRecyclerViewLayoutManager(LayoutManagerType.GRID_THREE_COLUMNS);
            item.setChecked(true);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void updateRecyclerViewLayoutManager(LayoutManagerType type) {
        currentLayoutManagerType = type;
        RecyclerView.LayoutManager layoutManager = null;
        switch (type) {
            case FLEXBOX:
                FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(getContext());
                flexboxLayoutManager.setFlexDirection(FlexDirection.ROW);
                flexboxLayoutManager.setFlexWrap(FlexWrap.WRAP);
                flexboxLayoutManager.setJustifyContent(JustifyContent.FLEX_START);
                layoutManager = flexboxLayoutManager;
                break;
            case GRID_ONE_COLUMN:
                layoutManager = new LinearLayoutManager(getContext());
                break;
            case GRID_TWO_COLUMNS:
                layoutManager = new GridLayoutManager(getContext(), 2);
                break;
            case GRID_THREE_COLUMNS:
                layoutManager = new GridLayoutManager(getContext(), 3);
                break;
        }
        if (layoutManager != null && binding != null) {
            binding.recyclerViewTools.setLayoutManager(layoutManager);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}